import codecs
import json
import os

import config_setting
import util_store

url_title_list = []
persist_shortcut_type_list = [
    "article",
    "video"
]


def traverse_tree(node):
    if node is None:
        return

    collection_info = node.get('Collection')
    if collection_info:
        print("Collection ID:", collection_info.get('id'))
        print("Collection Name:", collection_info.get('name'))

    shortcuts = node.get('Shortcuts')
    if shortcuts:
        print("Shortcuts:")
        for shortcut in shortcuts:
            print("\tShortcut ID:", shortcut.get('id'))
            print("\tShortcut Name:", shortcut.get('name'))
            if shortcut.get('type') in persist_shortcut_type_list:
                url_title_list.append((shortcut.get('link'), shortcut.get('title')))

    children = node.get('Children')
    if children:
        print("Children:")
        for child in children:
            traverse_tree(child)


def start(exported_json_filepath):
    dirpath = f"assets/{config_setting.batch_name}/slash_unpersisted"
    # source_json_filepath = "E:/102_1rzjjw_1714616381.json"
    with codecs.open(exported_json_filepath, mode='r', encoding='utf-8') as f:
        tree = json.load(f)

    # 遍历树状结构
    for node in tree:
        traverse_tree(node)
    if not os.path.isdir(dirpath):
        os.mkdir(dirpath)
    util_store.append_url_list_with_subsidiary(os.path.join(dirpath, "slash_url_list.txt"), url_title_list)


if __name__ == "__main__":
    exported_json_filepath = "E:/102_LzH13v_1717201617.json"
    start(exported_json_filepath)
